/*
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.android.packageinstaller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ServiceInfo;
import android.util.Log;

public class AppAddedReceiver extends BroadcastReceiver {
    private static final String TAG = "AppAddedReceiver";


	@Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
            String packageName = intent.getData().getSchemeSpecificPart();  
            if(isInputMethodApp(context, packageName)){
            	Log.d(TAG, packageName + "isInputMethodApp");
                try {
                	PackageManager pm = context.getPackageManager();
					pm.getPackageInfo("com.android.settings", PackageManager.GET_META_DATA);
					//跳转百度
					Intent voiceControlIntent = new Intent(); 
					voiceControlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					voiceControlIntent.setAction("android.settings.INPUT_METHOD_SETTINGS"); 
	                context.getApplicationContext().startActivity(voiceControlIntent); 
			    } catch (Exception e) {
					e.printStackTrace();
			    }
            }
        }
    }
    
    //判断安装应用是否是输入法类型应用
    public static boolean isInputMethodApp(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        boolean isInputMethodApp = false;
        try {
            PackageInfo pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_SERVICES);
            ServiceInfo[] sInfo = pkgInfo.services;
            if (sInfo != null) {
                for(int i = 0; i < sInfo.length; i++) {
                    ServiceInfo serviceInfo = sInfo[i];
                    if (serviceInfo.permission != null && 
                            serviceInfo.permission.equals("android.permission.BIND_INPUT_METHOD")) {
                        isInputMethodApp = true;
                        break;
                    }
                }
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isInputMethodApp;
    }
}
